package com.owbtgad.common.network

import android.util.Log
import com.fuusy.common.network.config.LocalCookieJar
import com.google.gson.Gson
import com.owbtgad.common.utils.AppCache
import com.owbtgad.common.utils.InsertHelp
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.internal.addHeaderLenient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

private const val TAG = "RetrofitManager"

object RetrofitManager {

    private val mOkClient :OkHttpClient= OkHttpClient.Builder()
        .callTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .followRedirects(false)
        .addInterceptor(HttpCommonInterceptor())
//        .addInterceptor(HttpCommonInterceptor.Builder().addHeaderParams("systemData",Gson().toJson(InsertHelp.getHeadMap(AppCache.getContext()))).build())
        .cookieJar(LocalCookieJar())
        .addInterceptor(HttpLoggingInterceptor { message -> Log.d(TAG, "log: $message") }.setLevel(HttpLoggingInterceptor.Level.BODY)).build()

    private var mRetrofit: Retrofit? = null


    fun initRetrofit(): RetrofitManager {
        /*val head = Headers.Builder().add("systemData",Gson().toJson(InsertHelp.getHeadMap(AppCache.getContext())))
        mOkClient?.apply {
            addHeaderLenient(head,"systemData")
        }*/
        mRetrofit = Retrofit.Builder()
            .baseUrl("http://test-api.10nmall-s.com")
            .client(mOkClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return this
    }

    fun <T> getService(serviceClass: Class<T>): T {
        if (mRetrofit == null) {
            throw UninitializedPropertyAccessException("Retrofit必须初始化")
        } else {
            return mRetrofit!!.create(serviceClass)
        }
    }
}